var requireDirectory = require('require-directory'); //自动化引入 router
const Router = require('koa-router')
const fs = require('fs')
const path = require('path')
const morgan = require('koa-morgan')//错误日记
class InitManager {
    static initCore(app){
        //入口方法
        this.app=app
 
        this.initLoadRouters()
        this.loadHttpException()
 
        InitManager.loadConfig()
        this.logger()
    }
    static initLoadRouters() {
        //第一个参数是模块 第二个是路径 第三个参数 是一个对象 visit:fubction
        const apiDirectory=`${process.cwd()}/routes` //绝对路径 
      requireDirectory(module,apiDirectory, { visit: whenLoadModule })
        function whenLoadModule(obj) {
            if (obj instanceof Router) {
                InitManager.app.use(obj.routes())
            }
        }
    }
    static loadConfig(path = '') {
        const configPath = path || process.cwd() + '/config/config.js'
        const config = require(configPath)
        global.config = config
    }

    static loadHttpException(){
        const errors=require('./http-exception')
        global.errs=errors
        
    }
    
    static logger(){
        const ENV = process.env.NODE_ENV
        console.log(ENV)
        if (ENV !== 'production') {
          // // 开发环境 / 测试环境
          // InitManager.app.use(morgan('dev'));
           // 线上环境
           console.log(process.cwd())
    
           const logFileName = path.join(process.cwd(), 'logs', 'access.log')
           const writeStream = fs.createWriteStream(logFileName, {
             flags: 'a'
           })

           InitManager.app.use(morgan('combined', {
             stream: writeStream
           }));
        } else {
          // 线上环境
          const logFileName = path.join(__dirname, 'logs', 'access.log')
          const writeStream = fs.createWriteStream(logFileName, {
            flags: 'a'
          })
          InitManager.app.use(morgan('combined', {
            stream: writeStream
          }));
        }
        
    }
}
module.exports=InitManager  